package cn.gson.school.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import cn.gson.school.entity.xitong.ImageEntity;
import cn.gson.school.entity.xitong.UserEntity;
import cn.gson.school.service.ImagesService;

@Controller
public class ImageController {

	Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * 获取配置文件中的属性值 配置文件需要通过Spring的 PropertyPlaceholderConfigurer进行加载
	 */
	@Value("${upload.dir}")
	private String uploadDir;

	@Autowired
	private ImagesService imgService;

	/**
	 * 上传
	 * 
	 * @param type
	 * @param file
	 * @return
	 */
	@PostMapping("/upload")
	@ResponseBody
	public ImageEntity upload(
			@SessionAttribute("user") UserEntity user,
			@RequestParam(defaultValue = "public") String type, 
			@RequestParam("file") MultipartFile file) {
		ImageEntity img = null;
		try {
			img = imgService.upload(user, type, file,null);
		} catch (Exception e) {
			log.error("上传失败！", e);
		}

		return img;
	}

	/**
	 * 预览
	 */
	@GetMapping("/upload/**")
	public void preview(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String path = request.getServletPath();
		log.info(path);
		//// Users/gson/upload/food/2017/10/d1b5c538-f2fb-4d7c-85f2-ffa138db4bf0.jpg
		path = path.replaceFirst("/upload/", uploadDir);
		ServletOutputStream os = response.getOutputStream();
		System.out.println("path"+path);
		File f = new File(path);
		if (!f.exists()) {
			// 附件不存在的时候，直接返回404
			response.sendError(404);
			return;
		}

		// 创建一个输入流
		FileInputStream fis = new FileInputStream(f);
		// 每次读取的字节数
		byte[] b = new byte[2048];
		// 每次实际读取到的字节长度
		int len = 0;
		while ((len = fis.read(b)) > 0) {
			// 进入循环，表示读取到了字节
			// 读到多少，就写出多少
			os.write(b, 0, len);
		}

		fis.close();
	}

	/**
	 * 下载
	 */
	@GetMapping("/download/{imageId}")
	public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable("imageId") Long imageId)
			throws IOException {
		System.out.println("dsf"+imageId);
		// 根据id获取附件信息
		ImageEntity att = imgService.get(imageId);

		if (att == null) {
			// 附件不存在的时候，直接返回404
			response.sendError(404);
			return;
		}

		// 设置下载响应头信息
		response.setContentLengthLong(att.getImageSize());
		response.setContentType(att.getContentType());
		// 设置附件存储的默认文件名
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String(att.getImageName().getBytes("UTF-8"), "ISO8859-1"));

		String path = uploadDir + att.getImagePath();
		ServletOutputStream os = response.getOutputStream();

		// 创建一个输入流
		FileInputStream fis = new FileInputStream(path);
		// 每次读取的字节数
		byte[] b = new byte[2048];
		// 每次实际读取到的字节长度
		int len = 0;
		while ((len = fis.read(b)) > 0) {
			// 进入循环，表示读取到了字节
			// 读到多少，就写出多少
			os.write(b, 0, len);
		}

		fis.close();
	}

	/**
	 * 删除
	 */
	@GetMapping("/img/drop/{imageId}")
	public String drop(@PathVariable("imageId") Long imageId, HttpServletResponse response) throws IOException {
		try {
			imgService.drop(imageId);
		} catch (FileNotFoundException e) {
			log.error("imageId:{}文件不存在！", imageId, e);
			response.sendError(404);
			return null;
		} catch (Exception e) {
			log.error("imageId:{}文件删除失败！", imageId, e);
		}
		return "redirect:/biz";
	}

}
